package com.test.auth_db_auto.config.oauth;

import com.test.auth_db_auto.support.BootSecurityProperties;
import com.test.auth_db_auto.support.oauth2.BootAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletResponse;

/**
 * @ Author: .Mr
 * @ ClassName MySecurityResourceServerConfig
 * @ Description TODO
 * @ date 2021/12/20 17:19
 * @ Version 1.0
 */
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(5)
public class MySecurityResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private BootAccessDeniedHandler accessDeniedHandler;   //无权访问处理器
    @Autowired
    private AuthenticationEntryPoint point;
    @Autowired
    private BootSecurityProperties properties;

    @Autowired
    private TokenStore tokenStore;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/oauth/**","/token/revoke",   //未登录时允许访问的url
                        properties.getLoginPage(),
                        properties.getBaseLogin().getLoginProcessUrl(),
                        properties.getSmsLogin().getLoginProcessUrl())
                .permitAll().anyRequest()
                .access("#oauth2.hasAnyScope('all','select')");
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore)
                .accessDeniedHandler(accessDeniedHandler)
                .authenticationEntryPoint(point);
    }
}
